<template>
  <div>
    <el-upload
      :class="{show:fileComputed}"
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :file-list="fileList"
      :on-remove="remove"
      :on-change="changeFile"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-progress v-if="showPercent" style="width: 180px" :percentage="percent"/>
    <el-dialog :visible.sync="dialogVisible" width="30%">
      <img width="100%" :src="dialogImageUrl" alt>
    </el-dialog>
  </div>
</template>
<script>
import COS from "cos-js-sdk-v5";
var cos = new COS({
  SecretId: "AKIDhCRP6WfYAxYsviDSQ7XgY9TXKq53lCMF", // 身份识别 ID
  SecretKey: "e06uSjjR0JK5ZnmTt3wYtynNghTxA6mD" // 身份密钥
});
export default {
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      showPercent: false,
      percent: 0
    };
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    remove() {
      this.fileList = [];
    },
    changeFile(file, fileList) {
      this.fileList.push(file);
    },
    beforeUpload(file) {
      // 要开始做文件上传的检查了
      // 文件类型 文件大小
      const types = ["image/jpeg", "image/gif", "image/bmp", "image/png"];
      if (!types.includes(file.type)) {
        this.$message.error("上传图片只能是 JPG、GIF、BMP、PNG 格式!");
        return false;
      }
      //  检查大小
      const maxSize = 5 * 1024 * 1024;
      if (maxSize < file.size) {
        this.$message.error("图片大小最大不能超过5M");
        return false;
      }
      this.showPercent = true;
      return true;
    },
    upload(params) {
      //   console.log(params.file);
      if (params.file) {
        cos.putObject(
          {
            Bucket: "houtai-1307511435" /* 必须 */,
            Region: "ap-nanjing" /* 存储桶所在地域，必须字段 */,
            Key: "params.file.name" /* 必须 */,
            StorageClass: "STANDARD",
            Body: params.file, // 上传文件对象
            onProgress: params => {
              this.percent = params.percent * 100;
            }
          },
          (err, data) => {
            console.log(err || data);
            if (!err && data.statusCode === 200) {
              this.fileList[0].url = "http://" + data.Location;
              this.fileList[0].upload = true;
              setTimeout(() => {
                this.showPercent = false; // 隐藏进度条
                this.percent = 0; // 进度归0
              }, 2000);
            } else {
              this.fileList = [];
              this.$message.error("上传失败");
              this.showPercent = false; // 隐藏进度条
              this.percent = 0; // 进度归0
            }
          }
        );
      }
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length === 1;
    }
  }
};
</script>
<style>
.show .el-upload {
  display: none !important;
}
</style>
